/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package util;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import common.Client;
import javax.swing.Icon;
import javax.swing.ImageIcon;
/**
 *
 * @author user
 */
public class copyFiles extends Thread
{
    public ArrayList<String> filesToSend = new ArrayList<String>();
  
    public String sources[], target;
    public File targetFile;
    boolean interrupted, stopped, inProgress, copyAll, includePath;
    JFrame Frame;
    JLabel lblPrepare, lblFileSending;
    JButton btnCancelar;
    //Toolkit tk1;
    public Client client= null;
    
    public copyFiles(String sources[], String target, boolean copyAll, Client client) 
    {
        this.sources= sources;
        this.target = target;
        this.copyAll= copyAll;
        this.client = client;
        
        inProgress = false;
        Frame = new JFrame();
        Frame.setTitle("Backup Fire");
        Frame.setSize(600, 200);
        Frame.setResizable(false);
        Frame.setFont(new java.awt.Font ("Arial", 0, 12));
        Frame.getContentPane().setLayout(null);
        //tk1 = java.awt.Toolkit.getDefaultToolkit();
        Icon image = new ImageIcon("images/loading.gif");
        JLabel lblImg = new JLabel(image); 
        lblImg.setBounds(300 , 50, 32, 32);
        Frame.getContentPane().add(lblImg);
        //Frame.setLocation((tk1.getScreenSize().width-Frame.getSize().width)/2, (tk1.getScreenSize().height-Frame.getSize().height)/2);
        
        lblPrepare = new JLabel();
        lblPrepare.setForeground(Color.black);
        lblPrepare.setBackground(new java.awt.Color (255, 255, 204));
        lblPrepare.setText("Preparando para backup!");
        lblPrepare.setBounds(50,50,500,25);
        Frame.getContentPane().add(lblPrepare);
        
        lblFileSending = new JLabel();
        lblFileSending.setForeground(Color.black);
        lblFileSending.setBackground(new java.awt.Color (255, 255, 204));
        lblFileSending.setText("Files");
        lblFileSending.setBounds(50,75,500,25);
        Frame.getContentPane().add(lblFileSending);
        
        btnCancelar = new JButton("Cancelar");
        btnCancelar.setBounds(50, 100, 100, 25);
        btnCancelar.setVisible(true);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
                }
            }
            );
        Frame.getContentPane().add(btnCancelar);
        Frame.setVisible(true);
    }
 
    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) 
    {
        int returnValue = JOptionPane.showConfirmDialog(Frame, "Cancelar Backup?", "Backup Fire", JOptionPane.YES_NO_OPTION);
        if (returnValue == JOptionPane.YES_OPTION) 
        { 
           try
           {
               join();
           } 
           catch (InterruptedException e) {}
           
            Frame.dispose();
            interrupted = true;
            stopped = true;
        }
    }     
    
    public void run() 
    {
        targetFile = new File(target);
        interrupted = false;
        stopped = false;        
        
        lblPrepare.setText("Preparando arquivos...");         
        if (inProgress == false) {
            inProgress = true;        
            for (int i=0; i<sources.length; i++)
                if (! interrupted) 
                   copyFolder(new File(sources[i]), targetFile, copyAll);
       
            /*Ftpeia the files*/
            MyFtp ftp = new MyFtp(lblFileSending);
            
            ftp.setUrl(client.getFtpUrl());
            ftp.setUser(client.getFtpUsername());
            ftp.setPassword(client.getFtpPassword());
            ftp.setWorkingDirectory(client.getFolderName());
            
            if( !ftp.connect())
            {
                JOptionPane.showMessageDialog(null,"Problemas ao tentar conectar ao FTP!");
                return;
            }
            
            for(String file : filesToSend)
                ftp.addFile(file);

            lblPrepare.setText("Enviando arquivos.");
            if(ftp.sendFiles())
                JOptionPane.showMessageDialog(Frame, "Backup Terminado!", "Backup Fire", JOptionPane.PLAIN_MESSAGE);                
            else
                JOptionPane.showMessageDialog(Frame, "Erro! "+ftp.getMsgError(), "Backup Fire", JOptionPane.PLAIN_MESSAGE);                
            ftp.disconnect();         
            

            Frame.repaint();
            
            inProgress = false;
            Frame.dispose();
            try
            {
                sleep(3000);
                join();
            } catch (InterruptedException e) {}              
        }
    } 
    
    public void copyFolder(File sourceFile, File targetFile, boolean copyAll) 
    {       
        int i, n, returnValue;
        File files[] = {sourceFile};
        File dd, dp;
        String temp;
        
        if (sourceFile.isDirectory()) 
            files = sourceFile.listFiles();
        
        String pp, pd;
        FileInputStream fi;
        FileOutputStream fo;
        BufferedInputStream bi;
        BufferedOutputStream bo;
        boolean result;
        //AWTEvent evtt;
        
        n = 0;
        pd = sourceFile.toString().replace(':', '-');
        if (sourceFile.isDirectory()) 
            if (pd.lastIndexOf(File.separatorChar) > -1) 
                pd = pd.substring(pd.lastIndexOf(File.separatorChar) , pd.length());
        else 
            pd = "";
        


        try 
        {
            n = files.length;
        }catch (Exception e){}
        
        for (i=0; i<n; i++)
        {
            if (!files[i].exists()) 
                break;
            if (stopped == true) 
                break;

            //Show the file in the Label
            temp = files[i].toString();
            //Format string for 30 or less characters
            if( temp.length() > 30)
                temp= temp.substring(0, 5)+"..."+temp.substring(temp.length()-20);
            lblFileSending.setText(files[i].toString());
            
            if (interrupted == true) {
               returnValue = JOptionPane.showConfirmDialog(Frame, "Cancelar Backup?", "Backup Fire", JOptionPane.YES_NO_OPTION);
                if (returnValue == JOptionPane.YES_OPTION) 
                { 
                   try
                   {
                       join();
                   } 
                   catch (InterruptedException e) {}
                   Frame.dispose();
                   stopped = true;
                   break;
                }
                else 
                {
                       interrupted = false;
                }    
            }

            pp = files[i].toString().replace(':', '-');

            if (pp.lastIndexOf(File.separatorChar) > -1) 
                pp = pp.substring(pp.lastIndexOf(File.separatorChar), pp.length());

            if (pp.startsWith(File.pathSeparator)) 
            {
                dd = new File(targetFile.toString() + pd + pp);
                dp = new File(targetFile.toString() + pd);
            }
            else 
            {
                dd = new File(targetFile.toString() + pd + File.separatorChar + pp);
                dp = new File(targetFile.toString() + pd);
            }               

            if (files[i].isFile())
            {
                if ((dd.lastModified() != files[i].lastModified()) || (copyAll))
                {
                    try
                    {
                        fi = new FileInputStream(files[i]);
                        bi = new BufferedInputStream(fi);
                        if (!dp.exists()) 
                            result = dp.mkdirs();

                        fo = new FileOutputStream(dd);
                        bo = new BufferedOutputStream(fo);
                        int ab;
                        while ((ab=bi.read()) != -1 )
                            bo.write(ab);
                        bo.flush();

                        fi.close();
                        fo.close();
                        bi.close();
                        bo.close();
                    }
                    catch (IOException e)
                    {
                        System.out.println("IO_Exception"+e);
                    }
                    dd.setLastModified(files[i].lastModified()); 
                    filesToSend.add(files[i].getAbsolutePath());
                }
            }
            else
            {
                result = dd.mkdirs();
                copyFolder(files[i], dp, copyAll);
            }
        }
    } 
}
